# _*_ coding: utf-8 _*_
"""
author: lianGang
email: 1542652663@qq.com
语音识别API 调度腾讯公开接口
参考接口文档 https://cloud.tencent.com/document/api/1093/37823
"""

# 腾讯云 应用秘钥
SecretId = "AKIDugiNmzIuHh2PwJqUbNuByDEzOW3clF0d"
SecretKey = "UygibDtv9BaVFgz2wyncNs66Tu6WvFPF"

import json
import os
import base64

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614 import asr_client, models


defaultPara = {
    "ChannelNum": 1,    # 通道数
    "EngineModelType": "16k_zh",    # 中文 16k
    "ResTextFormat": 0,
    "Data": "", # need to set
    "SourceType": 1 # 语音来源
}


def createClient():
    cred = credential.Credential(SecretId, SecretKey)
    httpProfile = HttpProfile()
    httpProfile.endpoint = "asr.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = asr_client.AsrClient(cred, "", clientProfile)
    return client


def createSpeechTask(file_path):
    # 文件格式固定 wav
    errmsg = None
    resp = None
    try:
        client = createClient()
        req = models.CreateRecTaskRequest()
        params = defaultPara.copy()
        with open(file_path, "rb") as f:
            temp = f.read()
        # temp = temp.decode(encoding="ISO-8859-1")
        result = base64.b64encode(temp)
        params["Data"] = str(result, encoding="utf-8")
        req.from_json_string(json.dumps(params))
        response = client.CreateRecTask(req)
        resp = response.to_json_string()
    except TencentCloudSDKException as err:
        errmsg = err
    return errmsg, resp


def queryTaskResult(taskId):
    resp = None
    errmsg = None
    try:
        client = createClient()
        req = models.DescribeTaskStatusRequest()
        params = {
            "TaskId": taskId
        }
        req.from_json_string(json.dumps(params))
        response = client.DescribeTaskStatus(req)
        resp = response.to_json_string()
    except TencentCloudSDKException as err:
        errmsg = err
    return errmsg, resp


if __name__ == "__main__":
    task_id = 1245806928
    print(queryTaskResult(task_id))
    pass